<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>视频上传与播放</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .upload-container {
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            border: 2px dashed #ccc;
            border-radius: 10px;
            text-align: center;
        }
        .progress {
            margin: 20px 0;
            display: none;
        }
        .video-container {
            margin-top: 30px;
            max-width: 800px;
            margin-left: auto;
            margin-right: auto;
        }
        #video {
            width: 100%;
            max-height: 600px;
        }
        .status {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
            display: none;
        }
        .status.success {
            background-color: #d4edda;
            color: #155724;
        }
        .status.error {
            background-color: #f8d7da;
            color: #721c24;
        }
        .video-list {
            max-width: 800px;
            margin: 30px auto;
        }
        .video-item {
            padding: 10px;
            border: 1px solid #ddd;
            margin-bottom: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
        .video-item:hover {
            background-color: #f8f9fa;
        }
        .quality-selector {
            margin: 10px 0;
            text-align: right;
        }
        .quality-btn {
            margin-left: 5px;
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 3px;
            background: white;
            cursor: pointer;
        }
        .quality-btn.active {
            background: #007bff;
            color: white;
            border-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="upload-container">
            <h2>视频上传</h2>
            <form id="uploadForm">
                <div class="mb-3">
                    <input type="file" class="form-control" id="videoFile" accept="video/*" required>
                </div>
                <div class="mb-3">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="uploadType" id="syncUpload" value="sync" checked>
                        <label class="form-check-label" for="syncUpload">同步上传（等待转码完成）</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="uploadType" id="asyncUpload" value="async">
                        <label class="form-check-label" for="asyncUpload">异步上传（快速返回）</label>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">上传视频</button>
            </form>
            <div class="progress">
                <div class="progress-bar" role="progressbar" style="width: 0%"></div>
            </div>
            <div class="status"></div>
        </div>

        <!-- 视频列表 -->
        <div class="video-list">
            <h2>视频列表</h2>
            <div id="videoList">
                <!-- 视频列表将在这里动态加载 -->
            </div>
        </div>

        <div class="video-container">
            <h2>视频播放</h2>
            <div class="video-status mb-2" id="videoStatus" style="display: none;">
                <div class="alert alert-info">
                    <div class="d-flex justify-content-between align-items-center">
                        <span>转码状态：<span id="transcodingStatus">处理中</span></span>
                        <div>
                            <span class="badge bg-secondary me-2" id="lowBadge">480p</span>
                            <span class="badge bg-secondary me-2" id="midBadge">720p</span>
                            <span class="badge bg-secondary me-2" id="highBadge">1080p</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="quality-selector" id="qualitySelector" style="display: none;">
                <button class="quality-btn" data-quality="low">480p</button>
                <button class="quality-btn" data-quality="mid">720p</button>
                <button class="quality-btn" data-quality="high">1080p</button>
            </div>
            <video id="video" controls></video>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/hls.js/1.5.18/hls.js"></script>
    <script>
        let currentHls = null;
        let currentVideoId = null;
        let statusCheckInterval = null;

        // 检查视频状态
        function checkVideoStatus(videoId) {
            fetch(`/api/videos/${videoId}/status`)
                .then(response => response.json())
                .then(data => {
                    const statusDiv = document.getElementById('videoStatus');
                    const transcodingStatus = document.getElementById('transcodingStatus');
                    const lowBadge = document.getElementById('lowBadge');
                    const midBadge = document.getElementById('midBadge');
                    const highBadge = document.getElementById('highBadge');
                    
                    // 更新状态显示
                    statusDiv.style.display = 'block';
                    transcodingStatus.textContent = data.status === 'COMPLETED' ? '已完成' : '处理中';
                    
                    // 更新清晰度标签
                    lowBadge.className = `badge ${data.lowReady ? 'bg-success' : 'bg-secondary'} me-2`;
                    midBadge.className = `badge ${data.midReady ? 'bg-success' : 'bg-secondary'} me-2`;
                    highBadge.className = `badge ${data.highReady ? 'bg-success' : 'bg-secondary'} me-2`;
                    
                    // 如果转码完成，停止轮询
                    if (data.status === 'COMPLETED') {
                        clearInterval(statusCheckInterval);
                    }
                })
                .catch(error => {
                    console.error('获取视频状态失败:', error);
                });
        }

        // 加载视频列表
        function loadVideoList() {
            fetch('/api/videos/list')
                .then(response => response.json())
                .then(videos => {
                    const videoList = document.getElementById('videoList');
                    videoList.innerHTML = videos.map(video => `
                        <div class="video-item" onclick="playVideo('${video.videoId}')">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-0">${video.fileName}</h6>
                                    <small class="text-muted">上传时间: ${new Date(video.createTime).toLocaleString()}</small>
                                </div>
                                <span class="badge bg-primary">${formatFileSize(video.fileSize)}</span>
                            </div>
                        </div>
                    `).join('');
                })
                .catch(error => {
                    console.error('加载视频列表失败:', error);
                });
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 切换清晰度
        function switchQuality(quality) {
            if (!currentVideoId) return;
            
            // 更新按钮状态
            document.querySelectorAll('.quality-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');
            
            // 重新加载视频
            playVideo(currentVideoId, quality);
        }

        document.getElementById('uploadForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const file = document.getElementById('videoFile').files[0];
            if (!file) return;

            const progressBar = document.querySelector('.progress-bar');
            const progressDiv = document.querySelector('.progress');
            const statusDiv = document.querySelector('.status');
            progressDiv.style.display = 'block';
            statusDiv.style.display = 'none';

            try {
                const formData = new FormData();
                formData.append('video', file);

                // 根据选择的上传方式决定使用哪个接口
                const uploadType = document.querySelector('input[name="uploadType"]:checked').value;
                const endpoint = uploadType === 'sync' ? '/api/videos/upload' : '/api/videos/upload/async';

                const response = await fetch(endpoint, {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('上传失败');
                }

                const data = await response.json();
                statusDiv.textContent = data.message || '上传成功！';
                statusDiv.className = 'status success';
                statusDiv.style.display = 'block';

                // 重新加载视频列表
                loadVideoList();
                
                // 播放视频
                playVideo(data.videoId);

                // 如果是异步上传，开始轮询视频状态
                if (uploadType === 'async') {
                    if (statusCheckInterval) {
                        clearInterval(statusCheckInterval);
                    }
                    statusCheckInterval = setInterval(() => checkVideoStatus(data.videoId), 5000);
                }
            } catch (error) {
                console.error('上传失败:', error);
                statusDiv.textContent = '上传失败：' + error.message;
                statusDiv.className = 'status error';
                statusDiv.style.display = 'block';
            }
        });

        function playVideo(videoId, quality = 'high') {
            currentVideoId = videoId;
            const video = document.getElementById('video');
            const qualitySelector = document.getElementById('qualitySelector');
            
            // 显示清晰度选择器和状态
            qualitySelector.style.display = 'block';
            document.getElementById('videoStatus').style.display = 'block';
            
            // 如果已经存在HLS实例，先销毁
            if (currentHls) {
                currentHls.destroy();
            }
            
            if (Hls.isSupported()) {
                currentHls = new Hls({
                    debug: false,
                    enableWorker: true,
                    lowLatencyMode: true,
                });
                
                // 根据选择的清晰度加载对应的播放列表
                const playlistUrl = `/api/videos/${videoId}/playlist_${quality}`;
                console.log('加载播放列表:', playlistUrl);
                
                currentHls.loadSource(playlistUrl);
                currentHls.attachMedia(video);
                currentHls.on(Hls.Events.MANIFEST_PARSED, () => {
                    video.play().catch(error => {
                        console.error('播放失败:', error);
                    });
                });
            } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
                video.src = `/api/videos/${videoId}/playlist_${quality}`;
            }

            // 开始检查视频状态
            if (statusCheckInterval) {
                clearInterval(statusCheckInterval);
            }
            checkVideoStatus(videoId);
            statusCheckInterval = setInterval(() => checkVideoStatus(videoId), 5000);
        }

        // 页面加载时获取视频列表
        document.addEventListener('DOMContentLoaded', () => {
            loadVideoList();
            
            // 添加清晰度切换事件监听
            document.querySelectorAll('.quality-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const quality = e.target.dataset.quality;
                    switchQuality(quality);
                });
            });
        });
    </script>
</body>
</html> 